<template>
  <div style="padding: 0 2px">
    <a-select :size="size" v-model="innerValue" allowClear :placeholder="placeholder"
              style="width: 100%" v-if="auth === 'edit'">
      <a-select-option
        v-for="item in dict.dictItems" :value="item.dictValue + ''">
        <span style="user-select: none">{{ item.dictTitle }}</span>
      </a-select-option>
    </a-select>
    <span v-else>
      {{ innerTitle }}
  </span>
  </div>
</template>
<script>

import {createProps} from '@/utils';
import {createField} from '@comp/hhd/design/FormDesigner/types';
import {getAction} from '@api/manage';

export default {
  name: 'SelectSInput',
  props: {
    auth: createProps(String, 'edit'),
    fieldConfig: createProps(Object, createField),
    value: {
      type: [String, Number],
      default: undefined
    },
    title: {
      type: [String, Number],
      default: undefined
    },
    size: createProps(String, 'default'),
  },
  data() {
    return {
      dict: {
        dict: undefined,
        dictName: undefined,
        dictItems: [],
      }
    };
  },
  methods: {
    select(item) {
      if (this.value === item.dictValue + '') {
        this.change();
      }
    },
    change(v) {
      this.$emit('update:value', v);
      this.getTitle(v);
      this.$emit('change', v);
      this.$emit('update', v);
    },
    getTitle(v) {
      if (!this.dict.dictItems || !this.dict.dictItems.length) return;
      let item = this.dict && this.dict.dictItems || [];
      item = item.find(i => i.dictValue + '' === (v || this.value));
      let res = item && item.dictTitle || undefined;
      this.$emit('update:title', res);
      return res;
    },
    loadDict() {
      getAction('/form/loadDictItems', {
        dictCode: this.fieldConfig.dict,
        dictType: this.fieldConfig.dictType
      }).then(({result}) => {
        result && (this.dict = result);
      });
    },
  },
  watch: {
    fieldConfig: {
      handler() {
        this.fieldConfig && this.fieldConfig.dict && this.loadDict();
      },
      immediate: true,
    },
    value: {
      handler(v) {
        this.getTitle(v);
      },
      immediate: true
    }
  },
  computed: {
    placeholder() {
      return this.fieldConfig.placeholder
    },
    innerTitle() {
      return this.title || this.getTitle();
    },
    innerValue: {
      get() {
        return this.value && (this.value + '') || undefined;
      },
      set(v) {
        this.change(v);
      },
    }
  }
};
</script>